<html>

<head>
    <meta name="viewport" content="width=device-width; initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
    <style>
        body {
            background: black;
        }

        #DRAG {
            touch-action:none;
        }

        .btn {
            width: 100%;
            height: 100%;
            border: none;
            text-align: center;
            background-size: 60% 60%;
            background-color: transparent;
            outline: none;
            background-repeat: no-repeat;
            background-position: center center;
        }

        .btn:hover {
            background-color: rgba(0, 0, 0, 0.3);
        }

        td {
            text-align: center;
        }

        * {
            -webkit-user-select: none;
            -webkit-user-drag: none;
        }

        #BAR {
            background: rgba(255, 255, 255, 0.7);
            position: absolute;
            z-index: 3;
            left: 50%;
            bottom: 0;
            text-align: center;
            height: 8vh;
            width: 50vh;
            min-height: 60px;
            min-width: 500px;
            border-radius: 10px;
            backdrop-filter: blur(2px);
            transform: translateX(-50%);
            transition: all 0.3s linear;
        }

        #RATIO {
            display: flex;
            background: rgba(255, 255, 255, 0.7);
            position: absolute;
            z-index: 2;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            height: 50px;
            border-radius: 10px;
            backdrop-filter: blur(2px);
            transition: all 0.3s linear;
            visibility: hidden;
            pointer-events: none;
        }

        #TIP {
            display: flex;
            background: rgba(255, 255, 255, 0.7);
            position: absolute;
            z-index: 3;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            height: 50px;
            border-radius: 10px;
            backdrop-filter: blur(2px);
            transition: all 0.3s linear;
            visibility: hidden;
            pointer-events: none;
        }

        .icon {
            width: 50px;
            height: 50px;
            border: none;
            text-align: center;
            background-size: 60% 60%;
            background-color: transparent;
            outline: none;
            background-repeat: no-repeat;
            background-position: center center;
        }

    </style>
    <title>图片查看</title>
    <link rel="stylesheet" href="file-manager/assets/basicContext.min.css">
    <link rel="stylesheet" href="file-manager/assets/themes/default.min.css">
</head>

<body style="overflow: hidden;">
    <img id='IMG' style="position: absolute; z-index: 1; visibility: hidden;" src="">
    <div id='DRAG' style="position: absolute; z-index: 2; width: 100%; height: 100%; left: 0px; top: 0px;"></div>
    <div id="RATIO">
        <div class='icon'
        style='background-image: url();'>
        </div>
        <b id='RATIO_TEXT' style="font-size: 20px; line-height: 50px; color: #000000; transform: translateX(-10%);">100%</b>
    </div>
    <div id="TIP">
        <div style="width: 10px;"></div>
        <b id='TIP_TEXT' style="font-size: 20px; line-height: 50px; color: #000000;">TIP</b>
        <div style="width: 10px;"></div>
    </div>
    <div id='BAR'>
        <table id="BAR_TABLE" style="width: 48vh; min-width: 480px; height: 100%; margin: auto;">
            <tr>
                <!-- Template <td><button class='btn' style='background-image: url(data:image/svg+xml;base64,"></button></td> -->
                <!-- toggle -->
                <td>
                    <button class='btn'
                        style='background-image: url();'></button>
                </td>
                <!-- Rotate Left -->
                <td>
                    <button class='btn'
                        style='background-image: url();'></button>
                </td>
                <!-- Rotate Right -->
                <td>
                    <button class='btn'
                        style='background-image: url();'></button>
                </td>
                <!-- Previous Image -->
                <td>
                    <button class='btn' id='prev'
                        style='background-image: url();'></button>
                </td>
                <!-- Next Image -->
                <td>
                    <button class='btn' id='next'
                        style='background-image: url();'></button>
                </td>
                <!-- Zoom In -->
                <td>
                    <button class='btn'
                        style='background-image: url();'></button>
                </td>
                <!-- Zoom Out -->
                <td>
                    <button class='btn'
                        style='background-image: url();'></button>
                </td>
                <!-- Download -->
                <td>
                    <button class='btn'
                        style='background-image: url();'></button>
                </td>
            </tr>
        </table>
    </div>
</body>
<script>
    const body = document.body
    const IMG = document.getElementById('IMG')
    const DRAG = document.getElementById('DRAG')
    const BAR = document.getElementById('BAR')
    const RATIO = document.getElementById('RATIO')
    const RATIO_TEXT = document.getElementById('RATIO_TEXT')
    const TIP = document.getElementById('TIP')
    const TIP_TEXT = document.getElementById('TIP_TEXT')
    let RATIO_TIMER = null
    let TIP_TIMER = null
    let _ratio = 1
    let url = decodeURIComponent(new RegExp('\\?url=(.*)').exec(window.parent.location.href)[1]).trim()
    IMG.src = url.split('&message_id=')[0]

    var centerX = -1    // to center, with % instead
    var centerY = -1
    var rotate = 0    // degree
    var zoom = 1
    var scale = 1 // store the zoom before scaling

    var toggle = false

    function deployLT() {
        if (centerX < 0 || centerY < 0) {
            centerX = 50
            centerY = 50
        }
        var cX = centerX * body.clientWidth / 100
        var hX = IMG.offsetWidth / 2
        var cY = centerY * body.clientHeight / 100
        var hY = IMG.offsetHeight / 2
        IMG.style.left = cX - hX
        IMG.style.right = cX + hX
        IMG.style.top = cY - hY
        IMG.style.bottom = cY + hY
    }

    function adapt(relative = null) {
        var absX, absY

        centerX = 50
        centerY = 50

        if (relative) {
            // force adjust
            if (body.clientWidth - IMG.offsetWidth > body.clientHeight - IMG.offsetHeight) {
                // use height
                var ratio = IMG.offsetWidth / IMG.offsetHeight
                IMG.style.height = body.clientHeight
                IMG.style.width = IMG.offsetHeight * ratio
                _ratio = body.clientHeight / IMG.naturalHeight
            }
            else {
                var ratio = IMG.offsetHeight / IMG.offsetWidth
                IMG.style.width = body.clientWidth
                IMG.style.height = IMG.offsetWidth * ratio
                _ratio = body.clientWidth / IMG.naturalWidth
            }
        }
        else if (relative == false) {
            // force adjust
            IMG.style.width = IMG.naturalWidth
            IMG.style.height = IMG.naturalHeight
            _ratio = 1
        }
        const w = IMG.offsetWidth, h = IMG.offsetHheight
        deployLT()
    }

    // Drag and pinch support
    var starT, starTLT
    var evCache = new Array()
    var touchInitialZoom, firstPinchDistanceX, firstPinchDistanceY

    DRAG.onpointerdown = function (ev) {
        var e = ev || window.event

        starT = [e.clientX, e.clientY]
        starTLT = [IMG.offsetLeft, IMG.offsetTop]
        evCache.push(e)
        touchInitialZoom = zoom
        window.addEventListener('pointermove', pointermove)
        window.addEventListener('pointerup', pointerup)
    }

    function pointermove(ev) {
        var e = ev || window.event
        for (var i = 0; i < evCache.length; i++) {
            if (ev.pointerId == evCache[i].pointerId) {
                evCache[i] = ev
                break;
            }
        }
        if (evCache.length == 1) {
            if (starT == null) return

            if (centerX < 0 || centerY < 0) {
                centerX = 50
                centerY = 50
            }
            
            IMG.style.left = e.clientX - starT[0] + starTLT[0]
            IMG.style.top = e.clientY - starT[1] + starTLT[1]

            centerX = (IMG.offsetRight - IMG.offsetLeft) * 50 / body.clientWidth
            centerY = (IMG.offsetBottom - IMG.offsetTop) * 50 / body.clientHeight
        }
        else if (evCache.length == 2) {
            const ev0 = evCache[0], ev1 = evCache[1]
            const distanceX = Math.abs(ev0.clientX - ev1.clientX), distanceY = Math.abs(ev0.clientY - ev1.clientY)
            if (!firstPinchDistanceX) firstPinchDistanceX = distanceX
            if (!firstPinchDistanceY) firstPinchDistanceY = distanceY

            const ratio = Math.sqrt(
                Math.pow(distanceX / firstPinchDistanceX, 2) + 
                Math.pow(distanceY / firstPinchDistanceY, 2)
            ) / Math.SQRT2 
            
            if (touchInitialZoom * ratio * _ratio >= 0.2 && touchInitialZoom * ratio * _ratio <= 20)
                setZoom(e, touchInitialZoom * ratio)
        }
    }

    function pointerup(ev) {
        for (var i = 0; i < evCache.length; i++) {
            if (evCache[i].pointerId == ev.pointerId) {
                evCache.splice(i, 1)
                break
            }
        }
        if (evCache.length == 1) starT = null
        if (evCache.length < 2) {
            touchInitialZoom = undefined
            firstPinchDistanceX = undefined
            firstPinchDistanceY = undefined
        }
        
        if (evCache.length == 0) {
            window.removeEventListener('pointermove', pointermove)
            window.removeEventListener('pointerup', pointerup)
        }
    }

    // deploy buttons

    function mkTransform(rotate, zoom, showTip = true) {
        if (showTip) {
            RATIO_TEXT.innerText = (_ratio * zoom * 100).toFixed(0) + '%'
            RATIO.style.visibility = 'visible'
            RATIO.style.opacity = 1
            if (RATIO_TIMER) clearTimeout(RATIO_TIMER)
            RATIO_TIMER = setTimeout(() => {
                RATIO.style.visibility = 'hidden'
                RATIO.style.opacity = 0
                RATIO_TIMER = null
            }, 2000)
        }
        return 'rotate(' + rotate + 'deg) scale(' + zoom + ',' + zoom + ')'
    }

    function resetZoom(showTip = true) {
        // toggle
        toggle = !toggle
        zoom = 1
        adapt(toggle)
        IMG.style.transform = mkTransform(rotate, zoom, showTip)
    }

    function rotateAntiClockwise() {
        rotate -= 90
        if (!rotate % 360) rotate = 0
        IMG.style.transform = mkTransform(rotate, zoom)
    }

    function rotateClockwise() {
        rotate += 90
        if (!rotate % 360) rotate = 0
        IMG.style.transform = mkTransform(rotate, zoom)
    }

    function zoomIn(e, ratio=0.2) {
        scale = zoom
        zoom *= (1 + ratio)
        if (zoom * _ratio > 20) zoom = 20 / _ratio
        IMG.style.transform = mkTransform(rotate, zoom)
        updatePosition(e)
    }

    function zoomOut(e, ratio=0.2) {
        scale = zoom
        zoom *= (1 - ratio)
        if (zoom * _ratio < 0.2) zoom = 0.2 / _ratio
        IMG.style.transform = mkTransform(rotate, zoom)
        updatePosition(e)
    }

    function setZoom(e, target) {
        scale = zoom
        zoom = target
        IMG.style.transform = mkTransform(rotate, zoom)
        updatePosition(e)
    }

    function download() {
        window.downloadImage(IMG.src, true)
    }

    function previousImg() {
        if (!window.imgs) return
        const index = window.imgs.indexOf(url)
        if (index > 0) {
            url = window.imgs[index - 1]
            reinit()
        } else {
            showTips('已经是第一张了')
        }
    }

    function nextImg() {
        if (!window.imgs) return
        const index = window.imgs.indexOf(url)
        if (index < window.imgs.length - 1) {
            url = window.imgs[index + 1]
            reinit()
        } else {
            showTips('已经是最后一张了')
        }
    }

    function reinit() {
        IMG.src = url.split('&message_id=')[0]
        _ratio = 1
        centerX = -1    // to center, with % instead
        centerY = -1
        rotate = 0    // degree
        zoom = 1
        scale = 1 // store the zoom before scaling
        toggle = false
        IMG.style = 'position: absolute; z-index: 1; visibility: hidden;'
    }

    function showTips(str) {
        TIP_TEXT.innerText = str
        TIP.style.visibility = 'visible'
        TIP.style.opacity = 1
        if (TIP_TIMER) clearTimeout(TIP_TIMER)
        TIP_TIMER = setTimeout(() => {
            TIP.style.visibility = 'hidden'
            TIP.style.opacity = 0
            TIP_TIMER = null
        }, 2000)
    }

    window.addEventListener('keydown', (e) => {
        const ltArrow = 37
        const rtArrow = 39
        const upArrow = 38
        const dnArrow = 40
        let _key
        if (e) _key = e.which
        else _key = window.event.keyCode
        if (_key == ltArrow) {
            if (!e.shiftKey) previousImg()
            else IMG.style.left = IMG.offsetLeft + 10 + 'px'
        } else if (_key == rtArrow) {
            if (!e.shiftKey) nextImg()
            else IMG.style.left = IMG.offsetLeft - 10 + 'px'
        } else if (_key == upArrow) {
            if (e.ctrlKey) zoomIn({ type: 'click' })
            else IMG.style.top = IMG.offsetTop + 10 + 'px'
        } else if (_key == dnArrow) {
            if (e.ctrlKey) zoomOut({ type: 'click' })
            else IMG.style.top = IMG.offsetTop - 10 + 'px'
        }
    })

    var btnactions = [
        resetZoom, rotateAntiClockwise, rotateClockwise, previousImg, nextImg, zoomIn, zoomOut, download
    ]

    var btns = document.getElementsByTagName('button')
    for (var i in btns) {
        btns[i].onclick = btnactions[i]
    }

    IMG.onload = () => {
        resetZoom(false)
        IMG.style.visibility = 'visible'
    }

    // ajust focus 
    function updatePosition(e) {
        var focus
        if (e.type === "click") {
            focus = { x: body.clientWidth / 2, y: body.clientHeight / 2 }
        }
        else {
            focus = { x: e.clientX, y: e.clientY }
        }

        var dx = (focus.x - IMG.offsetLeft - IMG.width / 2) * (1 - zoom / scale);
        var dy = (focus.y - IMG.offsetTop - IMG.height / 2) * (1 - zoom / scale);

        IMG.style.left = IMG.offsetLeft + dx + 'px'
        IMG.style.top = IMG.offsetTop + dy + 'px'

    }

    DRAG.onwheel = e => {
        const isTouchPad = (Math.abs(event.deltaY) < 100) && !window.disableTouchPad
        if (!e.ctrlKey && isTouchPad) {
            IMG.style.top = IMG.offsetTop + e.wheelDeltaY + 'px'
            IMG.style.left = IMG.offsetLeft + e.wheelDeltaX + 'px'
            return
        }
        if (e.shiftKey) {
            IMG.style.top = IMG.offsetTop + e.wheelDeltaY / 5 + 'px'
            IMG.style.left = IMG.offsetLeft + e.wheelDeltaX / 5 + 'px'
            return
        }
        const deltaY = (isTouchPad && Math.abs(e.deltaY) < 30) ? e.deltaY * 10 : e.deltaY
        if (deltaY < 0) {
            zoomIn(e, -deltaY / body.clientHeight)
        }
        else if (deltaY > 0) {
            zoomOut(e, deltaY / body.clientHeight)
        }
    }

    document.addEventListener('keydown', (e) => {
        if (e.repeat) return
        if (e.key === 'w' && e.ctrlKey === true || e.key === 'Escape') {
            window.close()
        }
    })

    var timer = setTimeout(() => {
        BAR.style.opacity = 0
    }, 5000)
    BAR.onmouseout = function () {
        if (timer) {
            clearTimeout(timer)
            timer = null
        }
        timer = setTimeout(() => {
            BAR.style.opacity = 0
        }, 1000)
    }
    BAR.onmouseover = function () {
        if (timer) {
            clearTimeout(timer)
            timer = null
        }
        BAR.style.opacity = 1
    }
    DRAG.addEventListener('contextmenu', (e) => {
        console.log(e)
        var items = []
        items.push({
            title: '下载',
            fn: function () {
                window.downloadImage(IMG.src)
            }
        })
        items.push({
            title: '另存为',
            fn: function () {
                download()
            }
        })
        items.push({
            title: '复制图片',
            fn: function () {
                window.copyImage(IMG.src)
            }
        })
        items.push({
            title: '复制 URL',
            fn: function () {
                navigator.clipboard.writeText(IMG.src)
            }
        })
        items.push({
            title: '添加为默认表情',
            fn: function () {
                window.saveSticker(IMG.src)
            }
        })
        basicContext.show(items, e)
    })
</script>
<script src="file-manager/assets/basicContext.min.js"></script>

</html>